package mongodb

import (
	"fmt"
	"gopkg.in/mgo.v2"
	"sync"
)

var (
	once sync.Once
	c    Connect
)

type Connect struct {
	Url           string
	UserName      string
	Password      string
	DbName        string
	Authmechanism string
	DataBase      *mgo.Database
}

func NewConnect(url, userName, password, dbName, authmechanism string) *Connect {
	once.Do(func() {
		//url = beego.AppConfig.String("mgo::url")
		//username := beego.AppConfig.String("mgo::username")
		//password := beego.AppConfig.String("mgo::password")
		//dbname = beego.AppConfig.String("mgo::dbname")
		//authmechanism := beego.AppConfig.String("mgo::authmechanism")
		c = Connect{Url: url,
			UserName:      userName,
			Password:      password,
			DbName:        dbName,
			Authmechanism: authmechanism}

		url := fmt.Sprintf("mongodb://%s:%s@%s/%s?authMechanism=%s",
			c.UserName, c.Password, c.Url, c.DbName, c.Authmechanism)
		mgoSe, err := mgo.Dial(url)
		if err != nil {
			panic(err)
		}
		// Optional. Switch the session to a monotonic behavior.
		mgoSe.SetMode(mgo.Monotonic, true)
		c.DataBase = mgoSe.DB(c.DbName)
	})
	return &c
}
